package com.jay.net.clazz.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

class EchoConnectionHandler extends ConnectionHandler {

	EchoConnectionHandler() {
		super();
	}

	EchoConnectionHandler(Socket socket) {
		super(socket);
	}

	/**
	 * @param socket
	 *            Socket: must be closed on exit
	 */
	@Override
	public void handleConversation(Socket socket) {
		try {
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			// read requests from the input until EOF
			byte[] buffer = new byte[8192];
			int count;
			while ((count = in.read(buffer)) >= 0) {
				// echo input to the output
				out.write(buffer, 0, count);
				out.flush();
				// 不关闭，client就会一直阻塞在read
				// out.close();
			} // loop terminates at EOF
		} catch (IOException e) {
			/* … */
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
			}
		} // end finally
	} // end run()
}
